package com.xds.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xds.common.utils.HttpUtils;
import com.xds.gulimall.member.entity.MemberLevelEntity;
import com.xds.gulimall.member.exception.PhoneExsitException;
import com.xds.gulimall.member.exception.UserNameExsitException;
import com.xds.gulimall.member.service.MemberLevelService;
import com.xds.gulimall.member.vo.MemberLoginVo;
import com.xds.gulimall.member.vo.MemberRegistVo;
import com.xds.gulimall.member.vo.SocialUse;
import com.xds.gulimall.member.vo.UserInfo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xds.common.utils.PageUtils;
import com.xds.common.utils.Query;

import com.xds.gulimall.member.dao.MemberDao;
import com.xds.gulimall.member.entity.MemberEntity;
import com.xds.gulimall.member.service.MemberService;

import javax.xml.ws.Action;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }
    //注册
    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity memberLevelEntity = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(memberLevelEntity.getId());
        checkUserName(vo.getUserName());
        checkPhone(vo.getPhone());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encodePassword);

        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhone(String phone) throws PhoneExsitException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExsitException();

        }
    }

        @Override
        public void checkUserName(String username) throws UserNameExsitException{

            Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
            if (count > 0) {
                throw new UserNameExsitException();

            }
        }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile", loginacct).or().eq("username",loginacct));
        if (entity==null){
            //用户名不存在或者邮箱不存在
            return null;
        }else {
            //用户名存在
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, entity.getPassword());
            if (matches){
                //密码匹配正确
                return entity;
            }else {
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUse socialUse) throws Exception {
        Map<String,String> ma=new HashMap<>();
        ma.put("access_token",socialUse.getAccess_token());
        HttpResponse doGet = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), ma);
        long uid=0;
        UserInfo userInfo=null;
        if (doGet.getStatusLine().getStatusCode()==200) {
            String string = EntityUtils.toString(doGet.getEntity());
              userInfo = JSON.parseObject(string, UserInfo.class);
              uid=userInfo.getId();
        }
        //注册合并逻辑
//        long uid = socialUse.getUid();
        //判断当前社交用户是否已经登陆过系统
        MemberEntity member = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (member!=null){
            //用户注册过 更新信息
            member.setAccessToken(socialUse.getAccess_token());
            member.setExpiresIn(socialUse.getExpires_in());
            baseMapper.updateById(member);
            return member;
        }else {
            //没有注册过
            MemberEntity entity = new MemberEntity();
            entity.setSocialUid(uid);
            entity.setNickname(userInfo.getName());
            entity.setAccessToken(socialUse.getAccess_token());
            entity.setExpiresIn(socialUse.getExpires_in());
            baseMapper.insert(entity);
            return entity;
           }
        }

}